package com.ly10111.customedittext.ime.dict;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.HashMap;

public class PyDict implements IDict {

    public SQLiteDatabase db = null;

    @Override
    public void open(Context context) {
        db = SQLiteDatabase.openDatabase(String.format("/data/data/%s/databases/dict.db0", context.getPackageName()), null, SQLiteDatabase.OPEN_READWRITE);
    }

    @Override
    public void close() {
        db.close();
    }

    @Override
    public ArrayList<DictBean> cursor(String text, HashMap<String, String> codeMap, boolean isWord, boolean isPhrases) {
        if (isPhrases && isWord) text = text.substring(text.length() - 1);
        ArrayList<DictBean> dList = new ArrayList<>();
        Cursor cursor;
        if (isPhrases) {
            if (isWord)
                cursor = db.rawQuery("select id,word from phrases where word like ? and length(word)>1 group by word order by use desc limit 50", new String[]{text + "%"});
            else
                cursor = db.rawQuery("select id,word from phrases where pyCode like ? and length(word)>1 group by word order by use desc limit 50", new String[]{text + "%"});
        } else {
            cursor = db.rawQuery("select id,word from words where pyCode like ? group by word order by use desc limit 50", new String[]{text + "%"});
            if (!cursor.moveToNext()) {
                cursor.close();
                return cursor(text, codeMap, false, true);
            } else cursor.moveToPrevious();
        }
        while (cursor.moveToNext()) {
            long id = cursor.getLong(0);
            String word = cursor.getString(1);
            if (isPhrases && isWord) word = word.substring(1, word.length());
            DictBean dictBean = new DictBean(id, word);
            dList.add(dictBean);
        }
        cursor.close();
        return dList;
    }

    @Override
    public void addUse(DictBean dictBean) {
        if (dictBean.getWord().length() == 1)
            db.execSQL("update words set use=use+1 where id=?", new String[]{dictBean.getId() + ""});
        else
            db.execSQL("update phrases set use=use+1 where id=?", new String[]{dictBean.getId() + ""});
    }

    @Override
    public HashMap<String, String> getDictCodeMap() {
        return null;
    }
}
